<?php 
if ($_SERVER['REQUEST_METHOD'] !== 'POST'
		|| !isset($_POST['year']) || !isset($_POST['week'])
		|| !isset($_POST['day']) || !isset($_POST['start'])
		|| !isset($_POST['end'])|| !isset($_POST['type'])
		|| !isset($_POST['origin'])) {
	header("HTTP/1.1 400 Bad Request");
	exit;
}
require_once 'db.inc.php';
require_once 'gcm.send.php';
$data = $_POST;

$result = mysql_query("SELECT user FROM ".TABLE_PREFIX."devices WHERE deviceId = '".$data['origin']."'");
if (mysql_num_rows($result) == 0) {
	header("HTTP/1.1 401 Unauthorized");
	exit;
}
$user_id = mysql_result($result, 0, "user");
if ($_POST['type'] == 'add') { // add the shift
	mysql_query(sprintf("INSERT INTO ".TABLE_PREFIX."shifts (user, year, week, day, start, end) VALUES (%d,%d,%d,%d,%f,%f)",
			$user_id,$data['year'],$data['week'],$data['day'],$data['start'],$data['end'])) or die(mysql_error());
	sendUpdateMessage($user_id, $data['year'], $data['week'], $data['origin']);
	header("HTTP/1.1 201 Created");
} else if ($_POST['type'] == 'delete') { // delete the shift
	mysql_query(sprintf("DELETE FROM ".TABLE_PREFIX."shifts WHERE user = %d AND year = %d AND week = %d AND day = %d AND start = %f AND end = %f",
			$user_id,$data['year'],$data['week'],$data['day'],$data['start'],$data['end']));
	sendUpdateMessage($user_id, $data['year'], $data['week'], $data['origin']);
	header("HTTP/1.1 201 Created");
} else if ($_POST['type'] == 'edit') { // delete the shift
	mysql_query(sprintf("UPDATE ".TABLE_PREFIX."shifts SET start = %.2f, end = %.2f WHERE user = %d AND year = %d AND week = %d AND day = %d AND start = %f AND end = %f",
			$data['pref_start']. $data['pref_end'], $user_id,$data['year'],$data['week'],$data['day'],$data['start'],$data['end']));
	sendUpdateMessage($user_id, $data['year'], $data['week'], $data['origin']);
	header("HTTP/1.1 201 Created");
}



?>